package net.xdclass.xdclass_shiro;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;

/**
 * @program: xdclass_shiro
 * @description: 单元测试用例执行顺序
 * @author: rZ
 * @create: 2020-01-08 14:59
 **/

public class QuickStartTest5_3 {

    @Test
    public void testAuthentication(){
        //创建工厂
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:jdbcrealm.ini");
        SecurityManager securityManager = factory.getInstance();
        //读取SecurityManager
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("xdclass","456");
        subject.login(usernamePasswordToken);
        System.out.println("认证结果："+subject.isAuthenticated());
        System.out.println("是否有对应的admin角色："+subject.hasRole("admin"));
        System.out.println("是否有权限："+subject.hasRole("admin"));
    }

    @Test
    public void test2(){
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/xdclass_shiro?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false");
        ds.setUsername("root");
        ds.setPassword("12345678");
        JdbcRealm jdbcRealm = new JdbcRealm();
        jdbcRealm.setDataSource(ds);
        jdbcRealm.setPermissionsLookupEnabled(true);
        defaultSecurityManager.setRealm(jdbcRealm);
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("xdclass","456");
        subject.login(usernamePasswordToken);
        System.out.println("认证结果："+subject.isAuthenticated());
        System.out.println("是否有对应的admin角色："+subject.hasRole("admin"));
    }
}
